class TabActivityMonitor {
  constructor() {
    this.isActive = true;
    this.lastActivityTime = Date.now();
    
    // Page Visibility API
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
    
    // Window focus/blur
    window.addEventListener('focus', this.handleFocus);
    window.addEventListener('blur', this.handleBlur);
    
    // 定时检查
    setInterval(this.checkActivity.bind(this), 1000);
  }
  
  handleVisibilityChange = () => {
    this.isActive = !document.hidden;
    this.logState();
  };
  
  handleFocus = () => {
    this.isActive = true;
    this.lastActivityTime = Date.now();
    this.logState();
  };
  
  handleBlur = () => {
    this.isActive = false;
    this.logState();
  };
  
  checkActivity() {
    // 双重验证
    const timeInactive = Date.now() - this.lastActivityTime;
    if (this.isActive && timeInactive > 2000) {
      this.isActive = false;
      console.log('通过超时检测到非活动状态');
    }
  }
  
  logState() {
    console.log(`标签页状态: ${this.isActive ? '活动' : '非活动'}`);
  }
  
  isTabActive() {
    return this.isActive;
  }
}

// 使用示例
const tabMonitor = new TabActivityMonitor();
setInterval(() => {
  if (tabMonitor.isTabActive()) {
    // 执行活动状态下的操作
  }
}, 1000);